<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace app\plugins\model;

use think\Db;

/**
 * 模型
 */
load_trait('controller/Jump');
class Verify
{
    use \traits\controller\Jump;

    private $times = 0;
    private $param = [];
    private $users = [];
    private $users_id = 0;

    // 构造函数
    public function __construct($param = [], $users = [])
    {
        // 统一接收参数处理
        $this->times = getTime();
        $this->param = !empty($param) ? $param : [];
        $this->users = !empty($users) ? $users : [];
        $this->users_id = !empty($this->users['users_id']) ? intval($this->users['users_id']) : 0;
        // 核销记录表
        $this->weappVerify = Db::name('weapp_verify');
        // 核销人员表
        $this->weappVerifyStaff = Db::name('weapp_verify_staff');
        // 核销门店表
        $this->weappVerifyStore = Db::name('weapp_verify_store');
        // 订单主表
        $this->shopOrder = Db::name('shop_order');
        // 订单副表
        $this->shopOrderDetails = Db::name('shop_order_details');
        // 获取核销插件信息
        $this->weappInfo = model('ShopPublicHandle')->getWeappVerifyInfo();
    }

    // 获取核销订单展示信息
    public function getVerifyOrder($isReturn = false)
    {
        // 查询核销订单
        $verify_code = input('param.verify_code/s', '');
        if (empty($verify_code)) $this->error('未检测到核销码');
        $where = [
            'verify_code' => trim($verify_code),
        ];
        $verifyOrder = $this->weappVerify->where($where)->find();
        if (empty($verifyOrder)) $this->error('未查询到相关核销订单');
        if (intval($this->users['verify']['store_id']) !== intval($verifyOrder['store_id'])) $this->error('您没有该订单所属门店核销权限');
        if (1 === intval($verifyOrder['verify_status'])) $this->error('订单已成功核销过');

        // 查询订单主体信息
        $where = [
            'order_id' => intval($verifyOrder['order_id'])
        ];
        $goodsOrder = $this->shopOrder->where($where)->find();
        if (empty($goodsOrder) || 1 !== intval($goodsOrder['order_status'])) $this->error('订单不存在或已成功核销过');
        $litpic = $this->shopOrderDetails->where($where)->order('details_id asc')->value('litpic');
        $result = [
            'order_id' => $goodsOrder['order_id'],
            'order_code' => $goodsOrder['order_code'],
            'litpic' => $this->getDefaultPic($litpic, true),
        ];
        // 返回数据
        if (!empty($isReturn)) {
            return ['verifyOrder' => $verifyOrder, 'goodsOrder' => $goodsOrder];
        } else {
            $this->unifyParamSuccess('查询成功', null, $result);
        }
    }

    // 获取核销订单核销详情
    public function getVerifyOrderDetails()
    {
        // 查询核销订单
        $order_id = input('param.order_id/s', '');
        if (empty($order_id)) $this->error('未检测到订单ID');
        // 查询订单主体信息
        $where = [
            'order_id' => intval($order_id),
        ];
        $goodsOrder = $this->shopOrder->where($where)->find();
        if (empty($goodsOrder)) $this->error('未查询到相关核销订单');
        $goodsOrder['add_time'] = MyDate('Y-m-d H:i:s', $goodsOrder['add_time']);
        $goodsOrder['pay_time'] = !empty($goodsOrder['pay_time']) ? MyDate('Y-m-d H:i:s', $goodsOrder['pay_time']) : '';
        // 订单明细表
        $goodsList = $this->shopOrderDetails->order('product_price desc, product_name desc')->where($where)->select();
        foreach ($goodsList as $key => $value) {
            // 商品规格处理
            $valueData = !empty($value['data']) ? unserialize($value['data']) : [];
            $productSpec = !empty($valueData['spec_value']) ? htmlspecialchars_decode($valueData['spec_value']) : '';
            $productSpec = !empty($productSpec) ? explode('<br/>', $productSpec) : [];
            $value['product_spec'] = '';
            foreach ($productSpec as $key_1 => $value_1) {
                if (!empty($value_1)) $value['product_spec'] .= trim(strrchr($value_1, '：'),'：') . '; ';
            }
            // 商品图片处理
            $value['litpic'] = $this->getDefaultPic($value['litpic'], true);
            $goodsList[$key] = $value;
        }
        $goodsOrder['goodsList'] = $goodsList;
        // 查询核销订单记录
        $goodsOrder['verifyOrder'] = $this->weappVerify->where($where)->find();
        // 返回数据
        $this->unifyParamSuccess('查询成功', null, $goodsOrder);
    }

    public function confirmVerifyOrder()
    {
        // 获取订单信息
        $order = $this->getVerifyOrder(true);

        // 更新订单主表信息
        $where = [
            'logistics_type' => 2,
            'order_id' => intval($order['goodsOrder']['order_id']),
            'verify_id' => intval($order['goodsOrder']['verify_id']),
        ];
        $update = [
            'order_status' => 3,
            'update_time' => getTime(),
            'confirm_time' => getTime()
        ];
        $result = $this->shopOrder->where($where)->update($update);
        if (!empty($result)) {
            $where = [
                'order_id' => intval($order['verifyOrder']['order_id']),
                'verify_id' => intval($order['verifyOrder']['verify_id']),
                'verify_code' => strval($order['verifyOrder']['verify_code']),
            ];
            // 更新核销订单记录
            $update = [
                'verify_status' => 1,
                'staff_id' => $this->users['verify']['staff_id'],
                'verify_time' => getTime(),
                'update_time' => getTime()
            ];
            $result = $this->weappVerify->where($where)->update($update);
            if (!empty($result)) {
                // 核销完成
                AddOrderAction($order['goodsOrder']['order_id'], $this->users_id, 0, 3, 1, 1, '核销成功', '核销员确认订单核销');
                $this->unifyParamSuccess('核销成功');
            } else {
                // 订单退回待核销状态
                $where = [
                    'logistics_type' => 2,
                    'order_id' => intval($order['goodsOrder']['order_id']),
                    'verify_id' => intval($order['goodsOrder']['verify_id']),
                ];
                $update = [
                    'order_status' => 1,
                    'update_time' => getTime()
                ];
                $this->shopOrder->where($where)->update($update);
            }
        }
        $this->error('核销失败');
    }

    // 获取核销门店列表
    public function getVerifyStoreList()
    {
        // 查询门店列表
        $where = [
            'store_status' => 1
        ];
        $field = '*';
        $order = 'store_id desc';
        if (!empty($this->param['latitude']) && !empty($this->param['longitude'])) {
            $result = Convert_GCJ02_To_BD09($this->param['latitude'], $this->param['longitude']);
            $lat = $result['lat'];
            $lng = $result['lng'];
            if (!empty($lat) && !empty($lng)) {
                $earth = 6378.138;
                $f_lat = 'store_latitude';
                $f_lng = 'store_longitude';
                $d_field = ", ({$earth}*2*ASIN(SQRT(POW(SIN(({$f_lat}*PI()/180-{$lat}*PI()/180)/2),2)+COS({$f_lat}*PI()/180)*COS({$lat}*PI()/180)* POW(SIN(({$f_lng}*PI()/180-{$lng}*PI()/180)/2),2)))*1000) as store_distance";
                $field .= $d_field;
                $order = 'store_distance asc';
            }
        }
        $pagesize = config('paginate.list_rows') ? config('paginate.list_rows') : 15;
        $verifyStore = $this->weappVerifyStore->field($field)->where($where)->order($order)->paginate($pagesize, false, ['query' => request()->param()]);
        !empty($verifyStore) && $verifyStore = $verifyStore->toArray();

        // 处理门店信息
        foreach ($verifyStore['data'] as $key => $value) {
            $value['store_province'] = get_region_name($value['store_province']);
            $value['store_city'] = get_region_name($value['store_city']);
            $value['store_area'] = get_region_name($value['store_area']);
//            if (empty($value['store_logo'])) $value['store_logo'] = '/public/static/common/images/logo.png';
            $value['store_logo'] = !empty($value['store_logo']) ? $this->getDefaultPic($value['store_logo']) : '';
            $value['store_coverpic'] = !empty($value['store_coverpic']) ? $this->getDefaultPic($value['store_coverpic']) : '';
            if (!empty($value['store_distance'])) {
                if (intval($value['store_distance']) < 1000) {
                    $value['store_distance'] = ceil($value['store_distance']);
                    $value['store_distance_unit'] = 'm';
                } else {
                    $value['store_distance'] = round($value['store_distance'] / 1000, 1);
                    $value['store_distance_unit'] = 'km';
                }
            }
            $location = Convert_BD09_To_GCJ02($value['store_latitude'], $value['store_longitude']);
            $value['store_latitude'] = $location['lat'];
            $value['store_longitude'] = $location['lng'];

            $verifyStore['data'][$key] = $value;
        }

        $result = [
            'verifyStore' => $verifyStore,
        ];
        $this->unifyParamSuccess('查询成功', null, $result);
    }

    // 订单核销插件核销订单商品详情处理
    public function verifyOrderDetails($result = [])
    {
        $verify = [];
        if (!empty($result['verify_id']) && !empty($result['order_id']) && !empty($result['users_id'])) {
            $where = [
                'a.order_id' => intval($result['order_id']),
                'a.users_id' => intval($result['users_id']),
                'a.verify_id' => intval($result['verify_id'])
            ];
            $field = 'b.*, a.*';
            $verify = $this->weappVerify->alias('a')->field($field)->where($where)->join('__WEAPP_VERIFY_STORE__ b', 'a.store_id = b.store_id', 'LEFT')->find();
            $verify['store_province'] = get_province_name($verify['store_province']);
            $verify['store_city'] = get_city_name($verify['store_city']);
            $verify['store_area'] = get_area_name($verify['store_area']);
        }

        return $verify;
    }

    // 默认图片处理
    private function getDefaultPic($pic_url = '', $domain = true, $tcp = '')
    {
        $pic_url = get_default_pic($pic_url, $domain);
        $pic_url = str_replace('/public/static/common/images/not_adv.jpg', '/public/static/common/images/default_litpic_1.png', $pic_url);
        if (!empty($tcp) && preg_match('/^\/\/.*$/', $pic_url)) $pic_url = $tcp . ':' . $pic_url;

        return $pic_url;
    }

    // 统一携带默认参数返回
    private function unifyParamSuccess($msg = '操作成功', $url = null, $result = [])
    {
        $result['loadShow'] = 1;
        // 核销功能设置
        $result['verifyConfig'] = $this->weappInfo['data'];
        // 获取商城店铺设置信息(后台-设置-店铺信息)
        $result['shopConf'] = model('ShopPublicHandle')->getWebShopConfig();
        // 返回结果
        $this->success($msg, $url, $result);
    }
}
